<template>
  <div class="list">
    <a-button type="primary" class="base-mb10" @click="openModal">+ {{ $t('self.userBind.tips14') }}</a-button>

    <a-form
        ref="searchFormRef"
        class="search-form base-mb15"
        :label-col="{ style: { minWidth: '80px' } }"
        :model="searchFormState"
        @finish="onSearchFinish"
    >
      <a-row :gutter="[10, 24]">
        <a-col :span="6">
          <a-form-item name="userName" :label="$t('self.userBind.tips1')">
            <a-input v-model:value="searchFormState.userName" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="mobile" :label="$t('self.userBind.tips2')">
            <a-input v-model:value="searchFormState.mobile" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="no" :label="$t('self.userBind.tips8')">
            <a-input v-model:value="searchFormState.no" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="userName" :label="$t('self.userBind.tips13')">
            <a-input v-model:value="searchFormState.userName" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="status" :label="$t('self.userBind.tips5')">
            <a-select v-model:value="searchFormState.status" :options="[
              { label: $t('self.userBind.status.tips0'), value: 0 },
              { label: $t('self.userBind.status.tips1'), value: 1 },
          ]" :placeholder="$t('self.pleaseChoose')" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="orgId" :label="$t('self.userBind.tips13')">
            <a-select allow-clear v-model:value="searchFormState.orgId" :options="searchOrgOptions" :fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"/>
          </a-form-item>
        </a-col>
        <a-col class="base-flex base-rows" :offset="1">
          <a-button type="primary" html-type="submit">{{ $t('self.searchButton') }}</a-button>
          <a-button class="base-ml10" @click="resetSearchForm">{{ $t('self.resetButton') }}</a-button>
        </a-col>
      </a-row>
    </a-form>

    <s-table ref="stableRef" :api-obj="tableConfig.apiObj" api-method="POST" :columns="sourceColumn" row-key="id" :light-index="tableConfig.lightIndex" :is-row-selection="false" @selectionChange="tableSelectionChange" :is-show-tool="false" :scroll="{ x: 1600 }">

      <template #bodyCell="{ column, record, index }">

        <!--status 2过期 1正常，0冻结-->
        <template v-if="column.key === 'status'">
          <template v-if="record[column.key] === 1">
            <sc-status-indicator type="success"></sc-status-indicator>
            {{ $t('self.userBind.status.tips1') }}
          </template>
          <template v-else-if="record[column.key] === 2">
            <sc-status-indicator type="danger"></sc-status-indicator>
            {{ $t('self.userBind.status.tips2') }}
          </template>
          <template v-else>
            <sc-status-indicator type="warning"></sc-status-indicator>
            {{ $t('self.userBind.status.tips0') }}
          </template>
        </template>

        <!--获取运营商名称-->
        <template v-if="column.key === 'orgId'">
          {{ getOrgNameByOrgId(record[column.key]) }}
        </template>

        <template v-if="column.key === 'action'">
            <span>
              <a href="javascript:void(0)" @click="openModal(record, index)">{{ $t('self.edit') }}</a>

              <a-divider type="vertical"/>
              <a-popconfirm
                  :title="$t('self.confirmDelete')"
                  :ok-text="$t('self.yesTxt')"
                  :cancel-text="$t('self.noTxt')"
                  @confirm="handleDelete(record, index)"
              >
                <a href="javascript:void(0)">{{ $t('self.delete') }}</a>
              </a-popconfirm>

              <a-divider type="vertical"/>
              <a href="javascript:void(0)" @click="openRechargeModal(record, index)">{{ $t('self.user.tips12') }}</a>
            </span>
        </template>

      </template>
    </s-table>

    <editModal ref="modalRef" @ok="stableRef.refresh()" @close=""></editModal>
    <rechargeModal ref="rechargeModalRef" @ok="stableRef.refresh()"></rechargeModal>

  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ScStatusIndicator from '@/components/scMini/scStatusIndicator.vue'
import { mainStore } from '@/stores/mainStore'
import editModal from './edit_modal.vue'
import rechargeModal from './recharge_modal.vue'
import { message } from 'ant-design-vue'

const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t
const route = useRoute()
const router = useRouter()
const useMainStore = mainStore()

const selectedKey = ref([])
const stableRef = ref(null)
const tableConfig = ref({
  apiObj: $API.backend.userBind.list,
  lightIndex: [] // 要高亮的行号
})
// 表格列
const sourceColumn = ref([])

onMounted(async () => {
  // 获取表格列
  resetDefaultOptionsByLang()
  // 获取运营商下拉数据
  searchOrgOptions.value = await proxy.getOrgSelectList(true)
})

// 监听 lang 状态
watch(
    () => useMainStore.lang, // 切换语言包时
    (curr, old) => {
      // console.log('语言包', curr)
      // 获取表格列
      resetDefaultOptionsByLang()
    }
);


const resetDefaultOptionsByLang = () => {
  sourceColumn.value = [
    {
      title: $T('self.userCharge.tips14'),
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: $T('self.userCharge.tips3'),
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: $T('self.userCharge.tips4'),
      dataIndex: 'mobile',
      key: 'mobile'
    },
    // {
    //   title: $T('self.userCharge.tips4'),
    //   dataIndex: 'mobile',
    //   key: 'mobile'
    // },
    {
      title: $T('self.user.tips9'),
      dataIndex: 'email',
      key: 'email'
    },
    // {
    //   title: 'City | Country',
    //   dataIndex: 'city',
    //   key: 'city',
    //   customRender: ({record}) => {
		// 	  return (record.city + '-' + record.country);
		//   },
    // },
    //todo
    {
      title: $T('self.userCharge.tips13'),
      dataIndex: 'totalMoney',
      key: 'totalMoney'
    },
    // {
    //   title: $T('self.userCharge.tips6'),
    //   dataIndex: 'totalMoney',
    //   key: 'totalMoney'
    // },
    {
      title: $T('self.order.tips31'),
      dataIndex: 'no',
      key: 'no'
    },
    {
      title: $T('self.businessStation.modal.col15'),
      dataIndex: 'cardType',
      key: 'cardType',
      customRender: ({text}) => {
        return (text == 1 ? "E-CARS":"MOTOS");
      },
    },
    {
      title: $T('self.userBind.tips5'),
      dataIndex: 'status',
      key: 'status'
    },
    // {
    //   title: $T('self.userBind.tips7'),
    //   dataIndex: 'dataType',
    //   key: 'dataType',
    //   // 自定义显示列
    //   customRender: ({text, record}) => {
    //     // 1会员卡，2普通卡
    //     if(text === 1) {
    //       return $T('self.userBind.dataType.tips1')
    //     }else if(text === 2){
    //       return $T('self.userBind.dataType.tips2')
    //     }else{
    //       return '--'
    //     }
    //   },
    // },

    {
      title: $T('self.userBind.tips18'),
      dataIndex: 'remark',
      key: 'remark'
    },
    {
      title: $T('self.userBind.tips9'),
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      // width: 300
    },
    {
      title: $T('self.createTimeTxt'),
      dataIndex: 'createTime',
      key: 'createTime',
      // width: 300
    },
    { title: $T('self.actionButton'), key: 'action', ellipsis: true, fixed: 'right', width: 200 }
  ]
}

const tableSelectionChange = (rows, record) => {
  selectedKey.value = rows
  // console.log('表格选择项', rows, record)
}

// =========start search表单
const searchFormRef = ref(null)
const searchFormState = ref({
  orgId: null,    // 运营商户
  userName: '',
  mobile: '',
  no: '',
  status: null
})
const searchOrgOptions = ref([])

const onSearchFinish = (values) => {
  stableRef.value.upData(values, 1)
}
// 重置搜索表单
const resetSearchForm = () => {
  searchFormRef.value.resetFields()
}
// =========end search表单

const modalRef = ref(null)
const openModal = (record, index) => {
  if (index !== undefined) {
    // 编辑
    tableConfig.value.lightIndex = [index] // 仅高亮当前行
    nextTick(() => {
      modalRef.value.edit(record)
    })
  } else {
    // 新增
    modalRef.value.add()
  }

}

const handleDelete = (record, index) => {
  $API.backend.userBind.delete.post({
    cardNo: record.no
  }).then(() => {
    message.success($T('self.message.success'))
    stableRef.value.refresh()
  }).catch(err => {
    message.error(err.msg || $T('self.message.error'))
  })
}

const rechargeModalRef = ref(null)
const openRechargeModal = (record, index) => {
  tableConfig.value.lightIndex = [index] // 仅高亮当前行
  nextTick(() => {
    rechargeModalRef.value.show(record)
  })
}

</script>

<style lang="scss" scoped>
.list {
  height: 100%;
  background: #ffffff;
  padding: 15px;

  .search-form {
    padding: 16px;
    background: rgb(247, 248, 250);

    :deep(.ant-form-item) {
      margin-bottom: 0;
    }
  }
}
</style>
